package com.bb.blog.biz.manage.model;

import lombok.Data;
import org.springframework.beans.BeanUtils;

import java.util.*;

@Data
public class SysMenuTree extends SysMenu {


    private List<SysMenuTree> children;

    public SysMenuTree() {
        super();
        this.children = new LinkedList<>();
    }

    public static List<SysMenuTree> buildTree(List<SysMenu> sysMenus) {
        return buildTree(sysMenus, null);
    }

    public static List<SysMenuTree> buildTree(List<SysMenu> sysMenus, String root) {
        List<SysMenuTree> tree = new LinkedList<>();
        Map<String, List<SysMenuTree>> treeMap = new HashMap<>(sysMenus.size());
        for (SysMenu sysMenu : sysMenus) {

            SysMenuTree sysMenuTree = new SysMenuTree();
            BeanUtils.copyProperties(sysMenu, sysMenuTree);
            // 将自己的children与map里的list 关联
            treeMap.compute(sysMenuTree.getCode(), (k, v) -> {
                if (v == null) {
                    return sysMenuTree.children;
                }
                sysMenuTree.setChildren(v);
                return v;
            });

            // 如果是顶级计入tree中
            if ((root == null && (sysMenuTree.getPcode() == null)) ||
                    (root != null && root.equals(sysMenuTree.getPcode()))) {
                tree.add(sysMenuTree);
            } else {  // 如果不是顶级 找到自己的队伍加入
                treeMap.compute(sysMenuTree.getPcode(), (k, v) -> {
                    if (v == null) {
                        v = new LinkedList<>();
                    }
                    v.add(sysMenuTree);
                    return v;
                });
            }
        }
        return tree;
    }


}
